package com.lanjiu.lib.communication.timer;

import com.lanjiu.pro.business.BusinessProtocolMessageStandard;
import com.lanjiu.lib.communication.IMSConfig;
import com.lanjiu.lib.communication.interf.IMSClientInterface;
import com.lanjiu.lib.utils.log.Logger;

import java.util.Timer;
import java.util.TimerTask;

/**
 * @description:
 * @author: Panwei
 * @date: 2019/12/13 16:35
 */
public class RequestTimeoutTimer extends Timer {

    private IMSClientInterface mImsClient;  //ims客户端
    private BusinessProtocolMessageStandard.CheckUnifiedEntranceMessage mRequest; // 发送的消息
    private RequestTimeoutTask mTask;

    public RequestTimeoutTimer(IMSClientInterface imsClient, BusinessProtocolMessageStandard.CheckUnifiedEntranceMessage request) {
        this.mImsClient = imsClient;
        this.mRequest = request;
        this.mTask = new RequestTimeoutTask();
        this.schedule(mTask, mImsClient.getRequestTimeoutMillis());
    }

    private class RequestTimeoutTask extends TimerTask {
        @Override
        public void run() {
            try {
                mImsClient.getMsgDispatcher().dispatchFailureMsg(mRequest, IMSConfig.MSG_CONTENT_TYPE_MESSAGE_SEND_TIMEOUT);
                if (mImsClient.getRequestTimeoutTimerManager() != null)
                    mImsClient.getRequestTimeoutTimerManager().remove(mRequest.getUnifiedEntranceMessage().getHead().getUniqueIdentify());
            } finally {
                if (mImsClient.getRequestTimeoutTimerManager() != null)
                    mImsClient.getRequestTimeoutTimerManager().remove(mRequest.getUnifiedEntranceMessage().getHead().getUniqueIdentify());
            }
        }
    }

    public void send() {
        Logger.print("正在重发请求，message=" + mRequest);
        mImsClient.sendMsg(mRequest, false);
    }

    public Object request() {
        return mRequest;
    }

    @Override
    public void cancel() {
        if (mTask != null) {
            mTask.cancel();
            mTask = null;
        }
        super.cancel();
    }
}
